package models

import (
	"github.com/astaxie/beego/validation"
		goerrors "github.com/go-errors/errors"
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	//"strconv"
	"3rd/mongo"
)

type Postman struct {
	Qid         string `bson:"_id" json:"qid"`
	Name        string `bson:"name" json:"name" valid:"Required"`
	MobilePhone string `bson:"mobilePhone" json:"mobilePhone" valid:"Required; Mobile"`
}

func (this *Postman) Valid(v *validation.Validation) {
	if err := GetPostmanByPhone(this.MobilePhone, this); err != nil {
		Log.Debug(err.Error())
		//v.SetError(strconv.Itoa(ValidateError), err.Error())
	}
}

func GetPostmanByPhone(phone string, man *Postman) error {
	return mongo.DO(db_postman, col_postman, func(c *mgo.Collection) (err error) {
		if err := c.Find(bson.M{"mobilePhone": phone}).One(&man); err != nil {
			return goerrors.New(err)
		}
		return nil
	})
}

func Register(man *Postman) error {
	return mongo.DO(db_postman, col_postman, func(c *mgo.Collection) (err error) {
		if err := c.Insert(man); err != nil {
			return goerrors.New(err)
		}
		return nil
	})
}

func Total(qid string, from, to int64) (count int, err error) {
	return count, mongo.DO(db_order, col_order, func(c *mgo.Collection) (err error) {
		pipe := c.Pipe([]bson.M{
			{"$match": bson.M{"state": COMPLETE, "postman._id": qid, "created": bson.M{"$gte": from, "$lt": to}}},
			{"$group": bson.M{"_id": nil, "count": bson.M{"$sum": "$sentBuckets"}}},
		})

		var out bson.M
		err = pipe.One(&out)
		if err != nil {
			return goerrors.New(err)
		}
		count = out["count"].(int)
		return
	})
}
